package com.ryan.rss.war.ui.fragment;

import java.util.List;

import com.ryan.rss.war.R;
import com.ryan.rss.war.activity.ContentActivity;
import com.ryan.rss.war.adapter.ArticleAdapter;
import com.ryan.rss.war.database.DBManager;
import com.ryan.rss.war.util.RSSItem;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ListView;

public class ArticleListFragment extends Fragment {

	public static final String LOGTAG = "ArticleListFragment";

	// 文章
	private ListView articleView;// 文章列表
	private List<RSSItem> dbList;// 从数据库中根据目录读取出来的数据,用于ListView显示.
	private ArticleAdapter articleAdapter;
	// 目录
	String category;
	// main layout
	View view;

	private ArticleListFragment() {

	}

	public ArticleListFragment(String category, List<RSSItem> data) {
		Log.v("ArticleListFragment", "     ");

		this.category = category;
		dbList = data;
		if (dbList == null || dbList.size() == 0) {
			Log.e("ArticleListFragment", "dbList is empty");
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.article_layout, null);
		initView();
		return view;
	}

	private void initView() {

		articleView = (ListView) view.findViewById(R.id.itemlist);
		if (dbList == null || dbList.size() == 0) {
			Log.e("ArticleListFragment", "dbList is empty");
		}

		// articleAdapter = new
		// ArticleAdapter(getActivity(),R.layout.article_list_item, dbList);
		articleAdapter = new ArticleAdapter(getActivity(),
				R.layout.article_item, dbList);

		articleView.setAdapter(articleAdapter);

		articleView
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						startContentActivity(dbList.get(position));
					}
				});
	}

	private void startContentActivity(RSSItem item) {

		Intent itemIntent = new Intent(getActivity(), ContentActivity.class);

		Bundle b = new Bundle();
		b.putLong("id", item.id);
		b.putString("title", item.title);
		b.putString("description", item.description);
		b.putString("link", item.link);

		itemIntent.putExtra("feed", b);
		startActivityForResult(itemIntent, 0);
		getActivity().overridePendingTransition(R.anim.zoom_enter,
				R.anim.push_left_out);

	}
}
